
import {getStore, setStore} from '@/framework-core/utils/store'
import {doMenu, doPermissions, encryption} from '@/framework-core/utils/util'
import {getUserInfo, loginByFace, loginByUsername, authlogin,logout, refreshToken, switchTenatRole,getPubMenusInfo} from '@/framework-core/api/login'


const user = {
  state: {
    dicts: {},
    userInfo:getStore({ name: 'userInfo' }) ||  {},
    permission:getStore({ name: 'permission' }) || [],
    roles:  getStore({ name: 'roles' }) || [],
    menuId: {},
    refreshFlg:getStore({ name: 'refreshFlg' }),
    pubMenus:getStore({ name: 'pubMenus' }),
    menu: getStore({ name: 'menu' }) || [],
    token: getStore({ name: 'token' }) || '',
    tokentemp: getStore({ name: 'tokentemp' }) || '',
    refreshToken: getStore({ name: 'token' }) || ''
  },
  actions: {
    //根据用户名登录
    LoginByUsername ({ commit }, userInfo = {}) {

      const user = encryption({
        data: userInfo,
        type: 'aes',
        key: 'kkkkkkk123456789',
        param: ['password']
      })


      return new Promise((resolve,reject) => {
        loginByUsername(user.username, user.password,user.captchaType,user.code,user.temptoken).then(res => {
          if(!res.data.success){
            reject(res.data.message);
            //that.$message.error(exam.data.message);
            return
          }
          const data = res.data.data.data || {}
          commit('SET_TOKEN', data.user.token);
          commit('DEL_ALL_TAG', []);
          commit('CLEAR_LOCK');
          commit('SET_USERIFNO', data.user);
          setStore({ name: 'pub_menus', content:0})
          resolve();
        })
      })
    },

    LoginByToken ({ commit }, token) {
      return new Promise((resolve,reject) => {
        authlogin(token).then(res => {
          debugger
          if(!res.data.success){
            reject(res);
            return
          }
          if(!res.data.data.user){
            reject(res);
            return
          }
          const data = res.data.data.data || {}
          commit('SET_TOKEN', data.user.token);
          commit('DEL_ALL_TAG', []);
          commit('CLEAR_LOCK');
          commit('SET_USERIFNO', data.user);
          commit('SET_PUB_MENUS', 0);
          resolve(res);
        })
      })
    },

    LoginByCasToken ({ commit }, res) {
      return new Promise((resolve,reject) => {
        if(!res.data.success){
          reject(res);
          return
        }
        if(!res.data.data.user){
          reject(res);
          return
        }

        const data = res.data.data.data || {}

        commit('SET_TOKEN', data.user.token);
        commit('DEL_ALL_TAG', []);
        commit('CLEAR_LOCK');
        commit('SET_USERIFNO', data.user);
        commit('SET_PUB_MENUS', 0);
        resolve(res);
      })
    },

    //人脸登录
    loginByFace ({ commit }, userInfo = {}) {


      return new Promise((resolve,reject) => {
        loginByFace(userInfo.username, userInfo.face,userInfo.temptoken).then(res => {
          if(!res.data.success){
            reject(res.data.message);
            //that.$message.error(exam.data.message);
            return
          }
          const data = res.data.data.data || {}
          commit('SET_TOKEN', data.user.token);
          commit('DEL_ALL_TAG', []);
          commit('CLEAR_LOCK');

          commit('SET_USERIFNO', data.user);
          commit('SET_PUB_MENUS', 0);
          resolve();
        })
      })
    },
    //根据手机号登录
    LoginByPhone ({ commit }, userInfo) {
      return new Promise((resolve) => {
        loginByUsername(userInfo.phone, userInfo.code).then(res => {
          const data = res.data.data;
          commit('SET_TOKEN',  data.user.token);
          commit('DEL_ALL_TAG', []);
          commit('CLEAR_LOCK');
          commit('SET_PUB_MENUS', 0);
          resolve();
        })
      })
    },
    GetUserInfo ({ commit }) {
      return new Promise((resolve, reject) => {
        getUserInfo().then((res) => {
          commit('SET_REFRESH_FLG', 2);
          const data = res.data.data.data || {}
          commit('SET_TOKEN', data.user.token);
          const menu = doMenu(data.menus, []);

          const permissions = doPermissions(data.permissions, [])

          commit('SET_MENU', menu)
          commit('SET_PERMISSIONS', permissions || [])
          commit('SET_USERIFNO', data.user);

          debugger
          const roles = [];
          if (data.roles) {
            data.roles.forEach(ele => {
              if(data.user.showOrg){
                roles.push({"label": ele.tenantName + "_" + ele.roleName+(ele.orgName?"_" + ele.orgName:"") , "value": (ele.tenantId||0) + "_" + ele.roleId+ "_" + (ele.orgId||"0"),"roleIcon":ele.roleIcon});
              }else{
                roles.push({"label": ele.tenantName + "_" + ele.roleName, "value": (ele.tenantId||0) + "_" + ele.roleId+ "_","roleIcon":ele.roleIcon});
              }

            })
          }
          commit('SET_ROLES', roles);

          resolve(data);
        }).catch(err => {
          reject(err);
        })
      })
    },
    GetPubMenus ({ commit }) {
      let $that = this;
      return new Promise((resolve, reject) => {
        getPubMenusInfo().then((res) => {
          const data = res.data.data.data || {}
          const menu = doMenu(data, []);
          commit('SET_REFRESH_FLG', 1);
          commit('SET_MENU', menu);
          debugger
          commit('SET_PUB_MENUS', 1);
          resolve(data);

        }).catch(err => {
          reject(err);
        })
      })
    },

    //刷新token
    RefreshToken ({ state, commit }) {
      return new Promise((resolve, reject) => {
        refreshToken(state.refreshToken).then(res => {
          const data = res.data.data;
          commit('SET_TOKEN', data);
          commit('SET_REFRESH_TOKEN', data);
            commit('SET_USERIFNO', data.user);
            commit('SET_REFRESH_FLG', 1);
          commit('SET_PUB_MENUS', 0);
          resolve(data);
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登出
    LogOut ({ commit }) {
      return new Promise((resolve, reject) => {
        logout().then(() => {
          setStore({ name: 'jrdic', content: "" })
          commit('SET_TOKEN', '')
          commit('SET_REFRESH_TOKEN', '');
        //  commit('SET_MENUALL_NULL', []);
          commit('SET_MENU', [])
          commit('SET_ROLES', [])
          commit('DEL_ALL_TAG', []);
          commit('CLEAR_LOCK');
            commit('SET_REFRESH_FLG', 1);
          commit('SET_PUB_MENUS', 0);
          commit('SET_PERMISSIONS',  [])
          commit('SET_USERIFNO', {});
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    switchTenatRole({ commit }, userInfo) {
      return new Promise((resolve, reject) => {

        if(!userInfo.trrId){
          userInfo.trrId = "";
        }
        let tps = userInfo.trrId.split("_");
        if(tps.length<2){
          reject("数据错误");
        }
        let org = tps.length>2?tps[2]:"";
        if(tps[0] == "null"){
          tps[0] = 0
        }

        switchTenatRole(tps[0],tps[1],org).then((res) => {

          const data = res.data.data.data || {}
          commit('SET_TOKEN', data.user.token);
            commit('SET_REFRESH_FLG', 1);
          commit('SET_MENU', [])
          commit('DEL_ALL_TAG', []);
          commit('CLEAR_LOCK');
          commit('SET_PUB_MENUS', 0);
          commit('SET_USERIFNO', data.user);

           resolve(data);
            }).catch(error => {
              reject(error)
            })
      })
    },

    //注销session
    FedLogOut ({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_REFRESH_TOKEN', '');
       // commit('SET_MENUALL_NULL', []);
        commit('SET_MENU', [])
        commit('SET_ROLES', [])
        commit('DEL_ALL_TAG', []);
        commit('CLEAR_LOCK');
          commit('SET_REFRESH_FLG', 1);
        commit('SET_PUB_MENUS', 0);

        resolve()
      })
    },
    GetTopMenu () {

      // return new Promise(resolve => {
      //   getTopMenu().then((exam) => {
      //     const data = exam.data.data || []
      //     resolve(data)
      //   })
      // })
    },
    //获取系统菜单
    GetMenu ({ commit }, parentId) {

      //commit('LIKE_TOP_MENUID', parentId)
      const  left= JSON.parse(JSON.stringify(this.getters.menu));
      return new Promise(resolve => {
        resolve(left)
      })
    },
  },
  mutations: {
    SET_DICTS(state, obj) {
      debugger
      state.dicts[obj.label] = obj.value;
    },
    SET_TOKEN: (state, token) => {
      state.token = token;
      setStore({ name: 'token', content: state.token })
    },
    SET_REFRESH_TOKEN: (state, token) => {
      state.refreshToken = token;
      setStore({ name: 'refreshToken', content: state.token })
    },
    SET_MENUID (state, menuId) {
      state.menuId = menuId;
    },
    SET_USERIFNO: (state, userInfo) => {
      state.userInfo = userInfo;
      setStore({ name: 'userInfo', content: state.userInfo })
    },
      SET_REFRESH_FLG: (state, refreshFlg) => {
          state.refreshFlg = refreshFlg
          setStore({name: 'refreshFlg', content: state.refreshFlg})
      },

    SET_PUB_MENUS: (state, pubMenus) => {
      state.pubMenus = pubMenus
      setStore({name: 'pubMenus', content: state.pubMenus})
    },

    SET_MENU: (state, menu) => {
      state.menu = menu
      setStore({ name: 'menu', content: state.menu })
    },

    SET_ROLES: (state, roles) => {
      state.roles = roles;
      setStore({ name: 'roles', content: state.roles })
    },
    SET_PERMISSIONS: (state, permission) => {
      state.permission = {};
      permission.forEach(ele => {
        state.permission[ele] = true;
      });
      setStore({ name: 'permission', content: state.permission })

    }
  }

}
export default user
